package com.lagou.edu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 处理multipart形式的数据
 */
@Controller
@RequestMapping("update")
public class UpdateController {

    /**
     * 文件上传
     * @param uploadFile
     * @param request
     * @return
     */
    @RequestMapping(value = "/file")
    public String upload(MultipartFile uploadFile, HttpServletRequest request, ModelMap modelMap) throws IOException {
        // ⽂件原名，如xxx.jpg
        String originalFilename = uploadFile.getOriginalFilename();
        // 获取⽂件的扩展名,如jpg
        String extendName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        // 新的⽂件名字
        String newName = UUID.randomUUID().toString() + "." + extendName;
        String realPath = request.getSession().getServletContext().getRealPath("/uploads");
        // 解决⽂件夹存放⽂件数量限制，按⽇期存放
        String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        File floder = new File(realPath + "/" + datePath);
        if(!floder.exists()) {
            floder.mkdirs();
        }
        uploadFile.transferTo(new File(floder,newName));
        modelMap.put("date", newName);
        return "success";
    }
}
